package com.superme.repository;

import com.superme.entity.PersonEntity;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.sql.Timestamp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PersonV2Specification<PersonEntity> extends SpecificationBase implements Specification<PersonEntity> {

    public PersonV2Specification() {

    }


    public String getSearchText() {
        return searchText;
    }

    public void setSearchText(String searchText) {
        this.searchText = searchText;
    }

    public PersonV2Specification(String searchText) {
        this.searchText = searchText;
    }

    /*
    定义查询字段
                 */
    private String searchText;


    @Override
    public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
        if (this.searchText == null) {

            return null;
        }
        if ((this.searchText.equals(""))) {
            return null;
        }
        //这边取的是类中的私有变量
        Path<String> namePath = root.get("name");
        Path<String> nicknamePath = root.get("nickname");
        Path<Integer> agePath = root.get("age");
        Path<Timestamp> birthdayPath = root.get("birthday");
        Path<Integer> heightPath = root.get("height");
        Path<Integer> idPath = root.get("id");

        // 连接查询条件, 不定参数，可以连接0..N个查询条件
        Predicate p = null;
        Predicate pName = cb.like(namePath, "%" + this.searchText + "%");
        p = this.SetOrConditions(p, cb, this.searchText, pName);
        Predicate pNickname = cb.like(nicknamePath, "%" + this.searchText + "%");
        p = SetOrConditions(p, cb, this.searchText, pNickname);

        if (this.isNumeric(searchText)) {
            Predicate pAge = cb.equal(agePath, this.searchText);
            p = SetOrConditions(p, cb, this.searchText, pAge);

            Predicate pHeight = cb.equal(heightPath, this.searchText);
            p = SetOrConditions(p, cb, this.searchText, pHeight);

            Predicate pId = cb.equal(idPath, this.searchText);
            p = SetOrConditions(p, cb, this.searchText, pId);

        }


        if (this.isDate(searchText)) {
            Date d = null;
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                d = sdf.parse(searchText);
                Timestamp ts = new Timestamp(d.getTime());
                Predicate pBirthday = cb.equal(birthdayPath, ts);
                p = SetOrConditions(p, cb, this.searchText, pBirthday);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }


        //这里可以设置任意条查询条件
        query.where(p);

        return null;
    }
}
